package com.jxzyk.util;

import java.util.List;

import com.jxzyk.R;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.ViewGroup;

public class FragmentPager {
	private FragmentManager manager;
	private List<Fragment> fragments;
	private int currentTab = 0; // 当前page索引（切换之前）
	private int resId = 0;

	public int getCurrentTab() {
		return currentTab;
	}

	public Fragment getCurrentFragment() {
		return fragments.get(currentTab);
	}

	public FragmentPager(FragmentManager manager, int resId,
			List<Fragment> fragments) {
		super();
		this.fragments = fragments;
		this.resId = resId;
		this.manager = manager;
		moveToIndex(0);
	}

	public void moveToIndex(int position) {
		for (int i = 0; i < fragments.size(); i++) {
			if (i == currentTab) {
				Fragment fragment = fragments.get(i);
				FragmentTransaction ft = manager.beginTransaction();
				getCurrentFragment().onPause(); // 暂停当前tab
				// getCurrentFragment().onStop(); // 暂停当前tab

				if (fragment.isAdded()) {
					// fragment.onStart(); // 启动目标tab的onStart()
					fragment.onResume(); // 启动目标tab的onResume()
				} else {
					ft.add(resId, fragment);
				}
				showTab(position); // 显示目标tab
				currentTab = position; // 更新目标tab为当前tab
				ft.commit();
			}
		}
	}

	public void showTab(int position) {
		for (int i = 0; i < fragments.size(); i++) {
			Fragment fragment = fragments.get(i);
			FragmentTransaction ft = manager.beginTransaction();
			if (position == i) {
				ft.show(fragment);
			} else {
				ft.hide(fragment);
			}
			ft.commit();
		}
	}

}
